<template>
  <el-dialog draggable title="分配科目" :close-on-click-modal="false" class="yy-modal--custom yy-modal--custom-sub yy-transfer--custom yy-base-item" width="800px" v-model="isVisible" @close="onCancelModel" :show-close="true">
    <div style="text-align: center;">
      <el-transfer
          :titles="['可添加终端', '已添加终端']"
          v-model="table.selectList"
          filterable
          :data="table.data"
      />
    </div>
    <template #footer>
        <span class="dialog-footer">
          <el-button @click="onCancelModel">关闭</el-button>
          <el-button type="primary" :loading="isSubmit" @click="onSave">保存</el-button>
        </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">

import {defineExpose, defineEmits, defineProps, reactive, ref} from "vue";
import DeviceApi from "@/api/queue/DeviceApi";
import {UsedTypeEnum} from "@/model/DeviceModel";
import RoomApi from "@/api/queue/RoomApi";
import {ElMessage} from "element-plus";

const $emit = defineEmits({
  saveSuccess: () => true
})

const props = defineProps({
  roomId: {
    type: String,
    required: true,
    default: null
  },
  usedType: {
    type: Number,
    required: true,
    default: null
  }
})

const isVisible = ref(false)
const isSubmit = ref(false)

const table = reactive({
  loading: false,
  selectList: [],
  data: []
})

const onShowModel = () => {
  isVisible.value = true
  listTerminal()
  listRoomTerminal()
}

const listTerminal = () => {
  DeviceApi.listDevice(null, null, props.usedType, 1, 999).then(res => {
    table.data = res.data.map(item => Object.assign({
      key: item.id,
      value: item.id,
      label: item.name,
      origin: item
    }))
  })
}

const listRoomTerminal = () => {
  if (!props.usedType) { return }
  RoomApi.listRoomTerminal(props.roomId, props.usedType).then((data) => {
    table.selectList = data.map(item => item.id)
  })
}

const onCancelModel = () => {
  isVisible.value = false
  table.selectList = []
  table.data = []
}

const onSave = () => {
  isSubmit.value = false
  RoomApi.addRoomTerminal(props.roomId, table.selectList, props.usedType).then(res => {
    ElMessage.success({
      message: '诊室终端分配成功',
      showClose: true
    })
    $emit('saveSuccess')
    onCancelModel()
    isSubmit.value = false
  }, () => isSubmit.value = false)
}
defineExpose({
  onShowModel
})
</script>
<style scoped lang="scss">
  .yy-base-item {
    &_empl {
      margin-bottom: 15px;
      display: flex;
      white-space: nowrap;
      align-items: center;
      background: #f5f7fa;
      padding: 8px 15px;
    }
  }
</style>